package com.currency.mall.ui.my.cash;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.entity.BankCardBean;
import com.currency.mall.entity.UserAccoutBean;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.my.AddBankCardActivity;
import com.currency.mall.ui.my.cash.CaseRecordActivity;
import com.currency.mall.util.IDCard;
import com.currency.mall.util.Util;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbusines.entity.ResponseBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/25.
 */

public class WithdrawalActivity extends BaseActivity {
    @BindView(R.id.tv_account_balance)
    TextView tvAccountBalance;
    @BindView(R.id.tv_available_balance)
    TextView tvAvailableBalance;
    @BindView(R.id.tv_withdrawal_price)
    TextView tvWithdrawalPrice;
    @BindView(R.id.tv_withdrawal_bank)
    TextView tvWithdrawalBank;
    @BindView(R.id.btn_withdrawal)
    Button btnWithdrawal;
    private UserAccoutBean userAccoutInfo;
    private List<String> bankNameList = new ArrayList<>();
    List<BankCardBean.BankCardInfo> bankCardInfos = new ArrayList<>();
    private String bankCodeId;//银行卡编号
    private Dialog addBankDilaog,caseeDialogShow;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        btnWithdrawal.getBackground().setAlpha(50);
        btnWithdrawal.setClickable(false);
        tvWithdrawalPrice.addTextChangedListener(textWatcher);
        tvWithdrawalBank.addTextChangedListener(textWatcher);
        getUserAccount();
        getBankCardList();
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String price = tvWithdrawalPrice.getText().toString().trim();
            String bank = tvWithdrawalBank.getText().toString().trim();
            if (TextUtils.isEmpty(price) || TextUtils.isEmpty(bank) || TextUtils.isEmpty(s)) {
                btnWithdrawal.setBackgroundResource(R.drawable.btn_bg);
                btnWithdrawal.getBackground().setAlpha(50);
                btnWithdrawal.setClickable(false);
            } else {
                btnWithdrawal.setBackgroundResource(R.drawable.btn_bg);
                btnWithdrawal.getBackground().setAlpha(250);
                btnWithdrawal.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    public void getUserAccount() {
        NetWork.getUserApi().accountQuery()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserAccoutBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(UserAccoutBean userAccoutBean) {
                        if (userAccoutBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            userAccoutInfo = userAccoutBean;
                            tvAccountBalance.setText(Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getTotalSum())));
                            tvAvailableBalance.setText(Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getUsabSum())));
                        } else {
                            ToastUitl.show(userAccoutBean.getMsg(), 200);
                        }
                    }
                });
    }

    public void getBankCardList() {
        NetWork.getUserApi().getBankCardData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BankCardBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BankCardBean bankCardBean) {
                        if (bankCardBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            if (bankCardBean.getList().size() > 0) {
                                bankCardInfos = bankCardBean.getList();
                                for (int i = 0; i < bankCardInfos.size(); i++) {
                                    BankCardBean.BankCardInfo bankCardInfo = bankCardInfos.get(i);
                                    bankNameList.add(bankCardInfo.getCardBank() + "  " + bankCardInfo.getCardId());
                                }
                            } else {
                                addBankCarDialog();
                            }

                        } else {
                            ToastUitl.show(bankCardBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void addBankCarDialog() {
        addBankDilaog = new Dialog(getContext(), R.style.dialog);
        addBankDilaog.setContentView(R.layout.dialog_not_title);
        addBankDilaog.show();
        addBankDilaog.setCancelable(false);
        TextView tvContent = (TextView) addBankDilaog.findViewById(R.id.tv_info);
        tvContent.setText("当前未添加银行卡");
        Button okBtn = addBankDilaog.findViewById(R.id.bt_ok);
        okBtn.setText("去添加");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addBankDilaog.dismiss();
                toAddBankCardIntent();

            }
        });
        Button cancleBtn = addBankDilaog.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void toAddBankCardIntent() {
        Intent intent = new Intent(getContext(),AddBankCardActivity.class);
        intent.putExtra("status",1);
        startActivityForResult(intent,1000);
        finish();
    }

    /**
     * 选择开户行
     */
    private void selectBank() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(getContext(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvWithdrawalBank.setText(bankNameList.get(options1));
                bankCodeId = bankCardInfos.get(options1).getId();
            }
        })
//                        .setSubmitText("确定")//确定按钮文字
//                        .setCancelText("取消")//取消按钮文字
//                        .setTitleText("城市选择")//标题
                .setSubCalSize(18)//确定和取消文字大小
//                        .setTitleSize(20)//标题文字大小
//                        .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.black_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.optional_color))//取消按钮文字颜色
//                        .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
//                        .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
//                        .setContentTextSize(18)//滚轮文字大小
//                        .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorCenter(getResources().getColor(R.color.optional_color))//设置选中项的颜色
                .setLineSpacingMultiplier(2.0f)//设置两横线之间的间隔倍数
//                        .setLinkage(false)//设置是否联动，默认true
//                        .setLabels("省", "市", "区")//设置选择的三级单位
//                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .setCyclic(false, false, false)//循环与否
//                        .setSelectOptions(1, 1, 1)  //设置默认选中项
//                        .setOutSideCancelable(false)//点击外部dismiss default true
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(bankNameList);
        pvOptions.show();
    }

    public void sumbitWithdrawal() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("money", tvWithdrawalPrice.getText().toString());
        hashMap.put("bankCodeId", bankCodeId);
        showLoading();
        NetWork.getUserApi().submitWithdrawal(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        hideLoading();
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("提现成功", 200);
                            finish();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }

                    }
                });
    }

    @OnClick({R.id.ll_back, R.id.tv_all_price, R.id.tv_withdrawal_bank, R.id.btn_withdrawal,R.id.ll_cash_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_all_price:
                tvWithdrawalPrice.setText(userAccoutInfo.getUserAccount().getUsabSum());
                break;
            case R.id.tv_withdrawal_bank:
                selectBank();
                break;
            case R.id.btn_withdrawal:
                caseDialogShow();
                break;
            case R.id.ll_cash_record:
                startActivity(new Intent(getContext(), CaseRecordActivity.class));
                break;
        }
    }

    private void caseDialogShow() {
        caseeDialogShow = new Dialog(getContext(), R.style.dialog);
        caseeDialogShow.setContentView(R.layout.dialog_not_title);
        caseeDialogShow.show();
        caseeDialogShow.setCancelable(false);
        TextView tvInfo = (TextView) caseeDialogShow.findViewById(R.id.tv_info);
        tvInfo.setText("确定提交提现申请吗？");
        Button okBtn = caseeDialogShow.findViewById(R.id.bt_ok);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                caseeDialogShow.dismiss();
                sumbitWithdrawal();
            }
        });
        Button cancleBtn = caseeDialogShow.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                caseeDialogShow.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 1002){
            getBankCardList();
        }
    }

}
